package com.xnfh.network.base

import android.media.session.MediaSession.Token
import com.xnfh.common.manager.UserInfoManager
import com.xnfh.common.provider.LoginServiceProvider
import com.xnfh.framework.Constants
import com.xnfh.framework.R
import com.xnfh.framework.bean.BaseResp
import com.xnfh.framework.bean.RespStateData
import com.xnfh.framework.ext.asActivity
import com.xnfh.framework.helper.SumAppHelper
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.framework.utils.ActManager
import com.xnfh.network.manager.TokenManager
import retrofit2.HttpException
import java.net.ConnectException
import java.net.UnknownHostException

/**
 * @Description:
 * @author ziheng
 * @date 2022/12/5 17:29
 */
open class BaseRepository {

    private val TAG = "BaseRepository"

    suspend fun <T> dealResp(
        block: suspend () -> BaseResp<T>,
        liveData: RespStateData<T>,
    ) {
        var result = BaseResp<T>()
        result.responseState = BaseResp.ResponseState.REQUEST_START
        liveData.postValue(result)
//        if (!NetWorkUtil.isNetworkConnected(ActManager.Instance().fristActivity)) {
//            result.responseState = BaseResp.ResponseState.REQUEST_FAILED
//            return
//        }

        try {

            //---------------------//
            result = block.invoke()
            //---------------------//
            LogUtil.d("$result", tag = TAG)
            val code = if(result.statusCode != -1){
                result.statusCode
            }else if(result.retCode != -1){
                result.retCode
            }else if(result.MessageId != -1){
                result.MessageId
            }else{
                result.status
            }

            when (code) {
                Constants.HTTP_SUCCESS -> {
                    result.responseState = BaseResp.ResponseState.REQUEST_SUCCESS
                }
                //天气相关的，后面code统一之后可以删掉
                Constants.HTTP_SUCCESS_WEATHER ->{
                    result.responseState = BaseResp.ResponseState.REQUEST_SUCCESS
                }
                //水肥机（三方接口）成功的状态码
                Constants.HTTP_SUCCESS_SFJ ->{
                    result.responseState = BaseResp.ResponseState.REQUEST_SUCCESS
                }
                Constants.HTTP_AUTH_INVALID -> {
                    result.responseState = BaseResp.ResponseState.REQUEST_LOGOUT
                    TipsToast.showWarningTips(R.string.common_logout)
                    LoginServiceProvider.logout(ActManager.Instance().currActivityContext)//跳转到用户登录页面
                    TokenManager.clearUserToken()//清除请求头的token
                    UserInfoManager.instance.loginOut()//清除用户信息

//                    UserInfoManager.instance.clearUserInfo()
//                    val eventMsg = EventMessageBean::class.java.newInstance()
//                    eventMsg.tag = EventBusTag.CLEAR_TOEKN_TAG
//                    EventBus.getDefault().post(eventMsg)
                }
                else -> {
                    result.responseState = BaseResp.ResponseState.REQUEST_FAILED
                    TipsToast.showWarningTips(result.message)
                }
            }

        } catch (e: Exception) {
            LogUtil.e(e.message.toString(),e,TAG)
            when (e) {
                is UnknownHostException,
                is HttpException,
                is ConnectException,
                -> {
                    //网络error
                    TipsToast.showWarningTips(e.message)
                }
                else -> {
                    TipsToast.showWarningTips(R.string.common_net_other_error)
                }
            }
            result.responseState = BaseResp.ResponseState.REQUEST_ERROR
        } finally {
            liveData.postValue(result)
        }
    }

}